package cn.glutnn.subject.domain.service.impl;

import cn.glutnn.subject.common.entity.PageResult;
import cn.glutnn.subject.common.enums.IsDeletedFlagEnum;
import cn.glutnn.subject.common.util.IdWorkerUtil;
import cn.glutnn.subject.common.util.LoginUtil;
import cn.glutnn.subject.domain.convert.SubjectInfoConverter;
import cn.glutnn.subject.domain.enyity.SubjectInfoBO;
import cn.glutnn.subject.domain.enyity.SubjectOptionBO;
import cn.glutnn.subject.domain.handler.subject.SubjectTypeHandler;
import cn.glutnn.subject.domain.handler.subject.SubjectTypeHandlerFactory;
import cn.glutnn.subject.domain.redis.RedisUtil;
import cn.glutnn.subject.domain.service.SubjectInfoDomainService;
import cn.glutnn.subject.domain.service.SubjectLikedDomainService;
import cn.glutnn.subject.infra.basic.entity.SubjectInfo;
import cn.glutnn.subject.infra.basic.entity.SubjectInfoEs;
import cn.glutnn.subject.infra.basic.entity.SubjectLabel;
import cn.glutnn.subject.infra.basic.entity.SubjectMapping;
import cn.glutnn.subject.infra.basic.service.SubjectEsService;
import cn.glutnn.subject.infra.basic.service.SubjectInfoService;
import cn.glutnn.subject.infra.basic.service.SubjectLabelService;
import cn.glutnn.subject.infra.basic.service.SubjectMappingService;
import cn.glutnn.subject.infra.entity.UserInfo;
import cn.glutnn.subject.infra.rpc.UserRpc;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Author:   msh
 * Date:     2024/11/27 上午12:06
 * Description:
 */

@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

    @Resource
    private SubjectInfoService subjectInfoService;
    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;
    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private SubjectEsService subjectEsService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private UserRpc userRpc;
    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;


    private static final String RANK_KEY = "subject_rank";



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl add subjectInfoBO:{}", subjectInfoBO);
        }
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectInfoService.save(subjectInfo);
        subjectInfoBO.setId(subjectInfo.getId());
        subjectTypeHandlerFactory.getHandler(subjectInfoBO.getSubjectType()).add(subjectInfoBO);
        LinkedList<SubjectMapping> subjectMappings = getSubjectMappings(subjectInfoBO, subjectInfo);
        subjectMappingService.saveBatch(subjectMappings);

        //同步到es
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setDocId(new IdWorkerUtil(1, 1, 1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectAnswer(subjectInfoBO.getSubjectAnswer());
        subjectInfoEs.setCreateTime(new Date().getTime());
        subjectInfoEs.setCreateUser("鸡翅");
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());
        subjectEsService.insert(subjectInfoEs);
        //redis放入zadd计入排行榜
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(), 1);

    }

    @Override
    public Page<SubjectInfoBO> querySubjectList(SubjectInfoBO subjectInfoBO) {
        LambdaQueryWrapper<SubjectMapping> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SubjectMapping::getCategoryId, subjectInfoBO.getCategoryId())
                .eq(SubjectMapping::getLabelId, subjectInfoBO.getLabelId());
        List<SubjectMapping> subjectMappingList = subjectMappingService.list(wrapper);
        List<Long> subjectIds = subjectMappingList.stream().map(SubjectMapping::getSubjectId).toList();
        LambdaQueryWrapper<SubjectInfo> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(SubjectInfo::getId, subjectIds)
                .eq(SubjectInfo::getIsDeleted, IsDeletedFlagEnum.UN_DELETED.getCode());
        Page<SubjectInfo> page = subjectInfoService.page(new Page<>(subjectInfoBO.getPageNo(), subjectInfoBO.getPageSize()), wrapper1);
        return (Page<SubjectInfoBO>) page.convert(SubjectInfoConverter.INSTANCE::convertInfoToBo);
    }

    @Override
    public SubjectInfoBO querySubjectDetail(SubjectInfoBO subjectInfoBO) {
        SubjectInfo subjectInfo = subjectInfoService.getById(subjectInfoBO.getId());
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        SubjectOptionBO optionBO = handler.query(subjectInfo.getId());
        SubjectInfoBO subjectInfoBO1 = SubjectInfoConverter.INSTANCE.convertInfoAndOptionToBo(subjectInfo, optionBO);
        // 查询标签
        LambdaQueryWrapper<SubjectMapping> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SubjectMapping::getSubjectId, subjectInfo.getId());
        List<SubjectMapping> subjectMappingList = subjectMappingService.list(wrapper);
        LambdaQueryWrapper<SubjectLabel> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(SubjectLabel::getId, subjectMappingList.stream().map(SubjectMapping::getLabelId).toList());
        List<SubjectLabel> labels = subjectLabelService.list(wrapper1);
        ArrayList<String> list = new ArrayList<>();
        labels.forEach(subjectLabel -> list.add(subjectLabel.getLabelName()));
        subjectInfoBO1.setLabelNames(list);
        subjectInfoBO1.setLiked(subjectLikedDomainService.isLiked(subjectInfoBO.getId().toString(), LoginUtil.getLoginId()));
        subjectInfoBO1.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBO.getId().toString()));
        assembleSubjectCursor(subjectInfoBO, subjectInfoBO1);
        return subjectInfoBO1;
    }

    private static LinkedList<SubjectMapping> getSubjectMappings(SubjectInfoBO subjectInfoBO, SubjectInfo subjectInfo) {
        LinkedList<SubjectMapping> subjectMappings = new LinkedList<>();
        List<Long> categoryIds = subjectInfoBO.getCategoryIds();
        List<Long> labelIds = subjectInfoBO.getLabelIds();
        categoryIds.forEach(categoryId -> {
            labelIds.forEach(labelId -> {
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setCategoryId(categoryId);
                subjectMapping.setLabelId(labelId);
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                subjectMappings.add(subjectMapping);
            });
        });
        return subjectMappings;
    }

    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());
        return subjectEsService.querySubjectList(subjectInfoEs);
    }

    @Override
    public List<SubjectInfoBO> getContributeList() {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (log.isInfoEnabled()) {
            log.info("getContributeList.typedTuples:{}", JSON.toJSONString(typedTuples));
        }
        if (CollectionUtils.isEmpty(typedTuples)) {
            return Collections.emptyList();
        }
        List<SubjectInfoBO> boList = new LinkedList<>();
        typedTuples.forEach((rank -> {
            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
            subjectInfoBO.setSubjectCount(rank.getScore().intValue());
            UserInfo userInfo = userRpc.getUserInfo(rank.getValue());
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(subjectInfoBO);

        }));
        return boList;

    }

    @Override
    public void assembleSubjectCursor(SubjectInfoBO subjectInfoBO, SubjectInfoBO bo) {
        Long categoryId = subjectInfoBO.getCategoryId();
        Long labelId = subjectInfoBO.getLabelId();
        Long subjectId = subjectInfoBO.getId();
        if (Objects.isNull(categoryId) || Objects.isNull(labelId)) {
            return;
        }
        Long nextSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 1);
        bo.setNextSubjectId(nextSubjectId);
        Long lastSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 0);
        bo.setLastSubjectId(lastSubjectId);
    }

}
